package com.guojiang.guopicturebackend.api.imagesearch.sub;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.guojiang.guopicturebackend.exception.BusinessException;
import com.guojiang.guopicturebackend.exception.ErrorCode;
import com.guojiang.guopicturebackend.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取以图搜图页面地址（Step 1）
 */
@Slf4j
public class GetImagePageUrlApi {

    /**
     * 获取以图搜图页面地址
     *
     * @param imageUrl
     * @return
     */
    public static String getImagePageUrl(String imageUrl) {
        // 1. 准备请求参数
        Map<String, Object> formData = new HashMap<>();
        formData.put("image", imageUrl);
        formData.put("tn", "pc");
        formData.put("from", "pc");
        formData.put("image_source", "PC_UPLOAD_URL");
        // 获取当前时间戳
        long uptime = System.currentTimeMillis();
        // 拼接请求地址
        String requestUrl = "https://graph.baidu.com/upload?uptime=" + uptime;
        try {
            // 2. 发送请求
            HttpResponse httpResponse = HttpRequest.post(requestUrl)
                    .form(formData)
                    .timeout(5000)
                    .execute();
            // 判断响应状态是否正常
            ThrowUtils.throwIf(httpResponse.getStatus() != HttpStatus.HTTP_OK
                    , ErrorCode.OPERATION_ERROR, "果酱识图接口调用失败");
            // 解析响应
            String body = httpResponse.body();
            Map<String, Object> resultData = JSONUtil.toBean(body, Map.class);
            // 3. 处理响应结果
            ThrowUtils.throwIf(resultData == null || !Integer.valueOf(0).equals(resultData.get("status"))
                    , ErrorCode.OPERATION_ERROR, "果酱识图接口调用失败");
            Map<String, Object> data = (Map<String, Object>) resultData.get("data");
            String rawUrl = (String) data.get("url");
            // 对原生url解码，否则可能会有一些不合法字符
            String searchResultUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);
            ThrowUtils.throwIf(StrUtil.isBlank(searchResultUrl), ErrorCode.OPERATION_ERROR, "接口返回数据无效");
            return searchResultUrl;
        } catch (Exception e) {
            log.error("果酱识图接口调用失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "果酱识图接口调用失败");
        }
    }
}
